<template>
  <div class="rental-service">
    <el-row :gutter="20">
      <el-col :span="8" v-for="room in roomList" :key="room.roomId">
        <el-card class="room-card">
          <div class="room-image">
            <img :src="getRoomImage(room)" :alt="room.roomTitle" @error="handleImageError" />
          </div>
          <div class="room-info">
            <h3>{{ room.roomTitle }}</h3>
            <p class="location">{{ room.roomAddress }}</p>
            <div class="room-details">
              <span>{{ room.roomType }}</span>
              <span>{{ room.roomArea }}㎡</span>
            </div>
            <div class="price-info">
              <span class="price">¥{{ room.roomPrice }}</span>
              <span class="unit">/月</span>
            </div>
            <div class="credit-info">
              <el-tag :type="canRent(room) ? 'success' : 'warning'" size="small">
                {{ getCreditTagText(room) }}
              </el-tag>
            </div>
          </div>
          <div class="room-actions">
            <el-button
              type="primary"
              size="small"
              @click="viewDetail(room)"
              style="margin-right: 10px;">
              查看详情
            </el-button>
            <el-button
              :type="canRent(room) ? 'success' : 'info'"
              size="small"
              @click="rentRoom(room)"
              :disabled="!canRent(room)">
              {{ getRentButtonText(room) }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 暂无数据 -->
    <div v-if="roomList.length === 0" class="no-data">
      <el-empty description="暂无房源信息"></el-empty>
    </div>
  </div>
</template>

<script>
import { listRooms, rentRoom } from '@/api/credit/businessService'

export default {
  name: "RentalService",
  props: {
    userScore: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      roomList: [],
      loading: false
    };
  },
  created() {
    this.getRoomList();
  },
  methods: {
    /** 获取房源列表 */
    getRoomList() {
      this.loading = true;
      listRooms().then(response => {
        if (response.code === 200) {
          this.roomList = response.data || [];
          // 确保requiredScore是数字类型
          this.roomList.forEach(item => {
            item.requiredScore = Number(item.requiredScore) || 0;
          });
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 检查是否可以租赁 */
    canRent(room) {
      const userScore = Number(this.userScore) || 0;
      const requiredScore = Number(room.requiredScore) || 0;
      return userScore >= requiredScore;
    },

    /** 获取信用标签文本 */
    getCreditTagText(room) {
      return this.canRent(room) ? '可租赁' : `需要${room.requiredScore}分`;
    },

    /** 获取租赁按钮文本 */
    getRentButtonText(room) {
      return this.canRent(room) ? '免押租赁' : '信用分不足';
    },

    /** 查看房源详情 */
    viewDetail(room) {
      this.$alert(`
        <div style="text-align: left;">
          <h3>${room.roomTitle}</h3>
          <p><strong>地址：</strong>${room.roomAddress}</p>
          <p><strong>房型：</strong>${room.roomType}</p>
          <p><strong>面积：</strong>${room.roomArea}㎡</p>
          <p><strong>租金：</strong>¥${room.roomPrice}/月</p>
          <p><strong>信用分要求：</strong>${room.requiredScore}分</p>
          <p><strong>描述：</strong>${room.roomDesc || '暂无详细描述'}</p>
        </div>
      `, '房源详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        customClass: 'room-detail-dialog'
      });
    },

    /** 获取房源图片 */
    getRoomImage(room) {
      if (room.roomImages) {
        try {
          const images = JSON.parse(room.roomImages);
          if (images && images.length > 0) {
            return this.getImageUrl(images[0]);
          }
        } catch (e) {
          console.warn('解析房源图片失败:', e);
        }
      }
      return '';
    },

    /** 处理图片加载错误 */
    handleImageError(event) {
      event.target.src = '';
    },

    /** 获取图片完整URL */
    getImageUrl(imagePath) {
      if (!imagePath) return '';
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath;
      }
      return process.env.VUE_APP_BASE_API + imagePath;
    },

    /** 租赁房源 */
    rentRoom(room) {
      if (!this.canRent(room)) {
        this.$message.warning(`您的信用分不足，需要${room.requiredScore}分才能享受免押租赁`);
        return;
      }
      this.$confirm(`确认租赁"${room.roomTitle}"？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const rentData = {
          roomId: room.roomId,
          checkInDate: new Date().toISOString().split('T')[0],
          months: 12
        };
        rentRoom(rentData).then(response => {
          if (response.code === 200) {
            this.$message.success(response.data.message || "租赁申请提交成功，请等待房东确认");
          } else {
            this.$message.error(response.msg || "租赁申请失败");
          }
        }).catch(() => {
          this.$message.error("租赁申请失败，请稍后重试");
        });
      });
    }
  }
};
</script>

<style scoped>
.room-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.room-card:hover {
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}

.room-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 15px;
}

.room-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
}

.location {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
}

.room-details {
  margin-bottom: 10px;
}

.room-details span {
  display: inline-block;
  background: #F5F7FA;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  margin-right: 8px;
}

.price-info {
  margin-bottom: 10px;
}

.price {
  color: #E6A23C;
  font-size: 20px;
  font-weight: bold;
}

.unit {
  color: #909399;
  font-size: 12px;
}

.credit-info {
  margin-bottom: 15px;
}

.room-actions {
  text-align: center;
}

.no-data {
  text-align: center;
  padding: 60px 0;
}
</style>
